package com.tinama.jedis01.demo;

import java.util.Date;

/**
 * @author lgc
 * @createDate 2020/10/10 - 17:47
 */
public class ShenXIao {
    public static void main(String[] args){
        Data data = new Data();
        new Thread(()->{for (int i=0;i<10;i++) {
            try {
                data.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"生产者1").start();
        new Thread(()->{for (int i=0;i<10;i++) {
            try {
                data.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"消费者1").start();
        new Thread(()->{for (int i=0;i<10;i++) {
            try {
                data.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"生产者2").start();
        new Thread(()->{for (int i=0;i<10;i++) {
            try {
                data.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"消费者3").start();
    }

    static class Data{
        /**
        *
        */
        private int number=0;

        public synchronized void increment() throws InterruptedException {
            while (number!=0){
                this.wait();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"生产了"+number);
            this.notifyAll();
        }
        public synchronized void decrement() throws InterruptedException {
            while (number==0){
                this.wait();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"消费了"+number);
            this.notifyAll();
        }

    }
}
